/*
 * ArrayList.cpp
 *
 *  Created on: 25.09.2012
 *      Author: Lapchinskiy
 */
#include "ArrayList.h"

ArrayList::ArrayList()
  {
    indexPointer = 0;
    length = defaultElementsNumber;
    arraybuf = new uint8_t*[length];
    indexPointer = 0;
  }
ArrayList::ArrayList(uint16_t elemNum)
  {
    this->length = elemNum;
    arraybuf = new uint8_t*[length];
    indexPointer = 0;
  }
ArrayList::~ArrayList()
  {
    delete[] arraybuf;
  }

ErrorCode ArrayList::add(void* newItem)
  {
    return add(newItem, indexPointer++);
  }

ErrorCode ArrayList::add(void* newItem, uint16_t index)
  {
    if (index >= length)
      {
        uint8_t** arraybufTemp = new uint8_t*[length];
        memcpy((void*) arraybufTemp, (void*) arraybuf,
            length * sizeof(uint8_t*));
        delete[] arraybuf;
        arraybuf = new uint8_t*[(length += listGrowStep)];
        memcpy((void*) arraybuf, (void*) arraybufTemp,
            ((length - listGrowStep) * sizeof(uint8_t*)));
        delete[] arraybufTemp;
      }
    if (index < length)
      {
        arraybuf[index] = (uint8_t*) newItem;
        return NO_ERR;
      }
    else
      {

      }
    return FAIL;

  }
ErrorCode ArrayList::remove(uint16_t index)
  {
    if (index > length)
      {
      }
    if (arraybuf[index] != 0)
      {
        arraybuf[index] = 0;
      }
    return NO_ERR;
  }

ErrorCode ArrayList::remove()
  {
    if (indexPointer > 0)
      {
        indexPointer--;
        arraybuf[indexPointer] = 0;
        return NO_ERR;
      }
    return FAIL;
  }
ErrorCode ArrayList::clear(void)
  {
    indexPointer = 0;
    delete[] arraybuf;
    arraybuf = new uint8_t*[length];
    return NO_ERR;
  }

void* ArrayList::get(uint16_t index)
  {
    if (index < indexPointer)
      {
        return (void*) arraybuf[index];
      }
    else
      {
        length = 0;
        index = 0;
      }
    return 0;
  }

uint16_t ArrayList::getSize() const
  {
    return this->length * sizeof(uint8_t);
  }

uint16_t ArrayList::getLength() const
  {
    return this->indexPointer;
  }
